package app

import "github.com/rs/zerolog/log"

type SetOption struct {
	DefaultCluster string
	ClusterName    string
	Node           Node
	Center         Center
}

func (m *Manager) Set(option *SetOption) {
	if option.Center.Addr != "" {
		m.Center = &option.Center
		log.Info().Msg("设置Center成功")
		return
	}
	if option.DefaultCluster != "" {
		m.DefaultCluster = option.DefaultCluster
		return
	}
	if option.ClusterName == "" {
		option.ClusterName = m.DefaultCluster
	}
	m.setNode(option)
}

func (m *Manager) setNode(option *SetOption) {
	if option.Node.IP == "" {
		return
	}
	if option.Node.Hostname == "" {
		client, err := m.getCenterSSHClient()
		if err != nil {
			log.Err(err).Msg("获取center ssh client失败")
			return
		}
		hostname, err := m.getNodeHostname(client, &option.Node)
		if err != nil {
			log.Err(err).Msg("获取hostname失败")
			return
		}
		if hostname == "" {
			log.Warn().Msg("获取hostname失败")
			return
		}
		option.Node.Hostname = hostname
	}
	cluster := m.GetCluster(option.ClusterName)
	if cluster == nil {
		cluster = &Cluster{
			Name: option.ClusterName,
		}
		m.Clusters[option.ClusterName] = cluster
	}
	for i, node := range cluster.Nodes {
		if node.Name == option.Node.Name {
			cluster.Nodes[i] = &option.Node
			log.Info().Msg("更新已存在的node成功")
			return
		}
	}
	cluster.Nodes = append(cluster.Nodes, &option.Node)
	log.Info().Msg("添加新node成功")
}
